package com.hospital.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.hospital.domain.utils.JwtUtils;
import com.hospital.domain.utils.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 令牌校验的拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//             //1. 获取请求头中的token
//             String token = request.getHeader("Authorization");
//
//             //2. 判断token是否存在, 如果不存在, 说明用户没有登录, 返回错误信息(响应401状态码)
//             if (token == null || token.isEmpty()){
//                 log.info("令牌为空, 响应401");
//                 response.setStatus(401);
//                 return false;
//             }
//
//             //3. 如果token存在, 校验令牌, 如果校验失败 -> 返回错误信息(响应401状态码)
//             Claims claims;
//             try {
//                 claims = JwtUtils.parseToken(token);
//             } catch (Exception e) {
//                 log.info("令牌非法, 响应401");
//                 response.setStatus(401);
//                 return false;
//             }
//
//             //4. 校验通过, 放行
//             log.info("令牌合法, 放行");
//             Map<String, Object> user = BeanUtil.beanToMap(claims.get("user"));
//             String uid = user.get("uid").toString();
            // UserContext.setUser(Long.parseLong(uid));
            return true;
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            UserContext.removeUser();
        }
    }

